package com.atguigu.petstore.sys.biz.impl;

import com.atguigu.petstore.common.constant.RedisConst;
import com.atguigu.petstore.common.util.CaptchaUtil;
import com.atguigu.petstore.sys.biz.SysCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * @author lfy
 * @Description
 * @create 2023-09-22 9:54
 */
@Service
public class SysCaptchaServiceImpl implements SysCaptchaService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public BufferedImage generateCaptcha(String deviceId) {

        //1、生成一个5位随机码
        String captcha = CaptchaUtil.generateRandomCaptcha(5);
        //为了不区分大小写统一用小写
        //将来验证只看 key是否在redis中有，如果有就删除
        String key = RedisConst.CAPTCHA_KEY +deviceId + ":" + captcha.toLowerCase();

        //验证码一分钟有效
        redisTemplate.opsForValue().set(key,"1",1, TimeUnit.MINUTES);

        //2、制作随机码图片
        BufferedImage img = CaptchaUtil.getCaptchaImg(captcha);
        return img;
    }
}
